'use strict';
const path = require('path');
const fs = require('fs');

const { Controller } = require('ee-core');
const Log = require('ee-core/log');
const Services = require('ee-core/services');
const { app, BrowserWindow,session,Menu, ipcMain } = require('electron');
const puppeteer = require('puppeteer-core');
const CoreWindow = require('ee-core/electron/window');
const { eleSend } = require('../utils/index');


/**
 * example
 * @class
 */
class ExampleController extends Controller {

  constructor(ctx) {
    super(ctx);
  }

  async localStorage(args, event) {
    let id = 7;
    console.log(args);
    const cookiesFilePath = path.join(__dirname, id+'storeage.json');
    fs.writeFileSync(cookiesFilePath, JSON.stringify(args));
  }
  /**
   * 所有方法接收两个参数
   * @param args 前端传的参数
   * @param event - ipc通信时才有值。详情见：控制器文档
   */

  /**
   * test
   */
  async test (args) {
    
    // const Addon = require('ee-core/addon');
    // const win = Addon.get('window');
    // const userDataPath = app.getPath('sessionData');

    // console.log(userDataPath);
    // return 
    // console.log(__dirname);
    const rootDir = app.getAppPath();
    // console.log('App Root Directory:', rootDir);
    // return 
    let url = 'https://discord.com'
    let id = '8';
    
    let mainWindow = new BrowserWindow({
      width: 800,
      show:false,
      height: 600,
      webPreferences: {
        preload: path.join(rootDir,'electron', 'preload.js'),
        nodeIntegration: false,
        contextIsolation: false,
          partition: id,
        // enableRemoteModule: true, // make sure you switch on these two options
      },
    });
    // mainWindow.webContents.setUserAgent('Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36');
     // 设置自定义的请求头
    // session.defaultSession.webRequest.onBeforeSendHeaders((details, callback) => {
    //   // if (details.url.startsWith(url)) {
    //   //   details.requestHeaders['from'] = 'your-email@example.com'; // 设置From头
    //   // }
    //   callback({ requestHeaders: details.requestHeaders });
    // });
    mainWindow.webContents.openDevTools();
  

  //   const cookiesFilePath = path.join(__dirname, id+'cookies.json');
  //   let cookies = [];
  //   if (!fs.existsSync(cookiesFilePath)) {
  //     cookies = [];
  //   }else{
  //   const cookiesData = fs.readFileSync(cookiesFilePath, 'utf8');
  //    cookies = JSON.parse(cookiesData);
  // }
    // 清除所有缓存
    // session.defaultSession.clearStorageData().then(async () => {
    //   console.log('Cache cleared');
      // 设置 Cookie
      // for (const cookie of cookies) {     
      // for (const cookie of cookies) {
      //   console.log('Set cookie:', cookie);
      //   try{

      //   await session.defaultSession.cookies.set({
      //     ...cookie,
      //     url: url, 
      //   });
     const win = CoreWindow.getMainWindow()
    
    //   // console.log(this.app.BrowserWindow.CoreWindo);
    //   // const win = this.electron.mainWindow;

      // mainWindow.hide()
      mainWindow.loadURL(url);
        // 使用 Promise 发送消息并等待响应

        const filter = {
          urls: ['wss://*/*'],
        };
        

        mainWindow.webContents.session.webRequest.onBeforeRequest(filter,(details, callback) => {
          console.log('拦截的请求:', details.url);
          callback({ cancel: false }); // 通过设置 cancel 为 true 可以取消请求
      });


      mainWindow.webContents.session.webRequest.onResponseStarted(filter, (details) => {
        // 开始处理响应数据
        console.log('响应开始:', details);
      });
    
     
     
      mainWindow.webContents.once('dom-ready', () => {
          eleSend(mainWindow,ipcMain,'set-localStorage',args).then((res)=>{
              console.log(res)
              mainWindow.loadURL(url+'/app');

              mainWindow.webContents.once('dom-ready', () => {
                // 你要注入的 JavaScript 代码
                const script = `
                  (function() {
                    const originalWebSocket = window.WebSocket;
            
                    // 替换原始的 WebSocket 对象
                    window.WebSocket = function (...args) {
                      const ws = new originalWebSocket(...args);
            
                      // 监听 WebSocket 的消息事件
                      ws.addEventListener('message', (event) => {
                        console.log('拦截到 WebSocket 消息:', event.data);
                        // 你可以在这里修改消息内容或做其他处理
                      });
            
                      return ws;
                    };
                  })();
                `;
            
                mainWindow.webContents.executeJavaScript(script).then(() => {
                  console.log('JavaScript 代码已注入');
                }).catch((error) => {
                  console.error('注入 JavaScript 代码失败:', error);
                });
              });
    
              
              // win.close();
              mainWindow.show()

          

          }).catch((error)=>{
            console.log(error)
          })
        // console.log(storages)
        // Object.entries((storages)).forEach(([key, value]) => {
        //           console.log(key,value)
               
        //           // });
        // });
        // win.loadURL(url+'/login');
      })
      mainWindow.openDevTools();
      // }catch(error){
      //   console.error('Failed to set cookie:', error);
      // }
    // });
      
      // }
       // 在设置完 Cookie 后加载 URL
       // 打开ChatGPT网站
  //      mainWindow.loadURL(url);
  //      try{

  //      const ses = mainWindow.webContents.session
  //      console.log('getUserAgent',ses.getStoragePath())
  //     }catch(error){
  //       console.error('Failed to set cookie:', error);
  //     }
  //      const storeageFilePath = path.join(__dirname, id+'storeage.json');
  //      let storages = [];
  //      if (!fs.existsSync(storeageFilePath)) {
  //       storages = [];
  //      }else{
  //      const storeageData = fs.readFileSync(storeageFilePath, 'utf8');
  //       storages = JSON.parse(storeageData);
  //      }
  //      console.log('storages',storages)
       
  //      mainWindow.webContents.on('dom-ready', () => {
      
  //       Object.entries((storages)).forEach(([key, value]) => {
  //         // console.log(key,value)
  //           mainWindow.webContents.send('set-localStorage', key, value);
  //         });
  //      });
  //        // 创建自定义菜单，包括返回按钮
  // const menu = Menu.buildFromTemplate([
  //   {
  //     label: 'Navigation',
  //     submenu: [
  //       {
  //         label: 'Back',
  //         accelerator: 'CmdOrCtrl+Left',
  //         click: () => {
  //           if (mainWindow.webContents.canGoBack()) {
  //             mainWindow.webContents.goBack();
  //           }
  //         },
  //       },
  //       {
  //         label: 'Forward',
  //         accelerator: 'CmdOrCtrl+Right',
  //         click: () => {
  //           if (mainWindow.webContents.canGoForward()) {
  //             mainWindow.webContents.goForward();
  //           }
  //         },
  //       },
  //     ],
  //   },
  // ]);

  // Menu.setApplicationMenu(menu);

  //   }).catch(error => {
  //     console.error('Failed to clear cache:', error);
  //   });

  // // 
 
  
    // 当页面加载完成后获取Cookies
    // mainWindow.webContents.on('did-finish-load', async () => {
    //   console.log('did-finish-load')
    //   const cookies = await session.defaultSession.cookies.get({url: url});
    //   console.log('Cookies:', cookies);
    //   // 输出Cookies到控制台
    //   cookies.forEach(cookie => {
    //     console.log(`${cookie.name}: ${cookie.value}`);
    //   });
    // });
   



    // 在窗口关闭时执行清理操作
    // mainWindow.on('closed',async () => {
    //   console.log('Window closed');

    //   try {
    //     // 获取指定域名的 Cookie
    //     const cookies = await session.defaultSession.
    //     console.log('Cookies:', cookies);
    //     // 将 Cookie 数据存储到本地文件
    //     const cookiesFilePath = path.join(__dirname, id+'cookies.json');
    //     fs.writeFileSync(cookiesFilePath, JSON.stringify(cookies, null, 2));
    //     console.log(`Cookies saved to ${cookiesFilePath}`);
    //   } catch (error) {
    //     console.error('Failed to get cookies:', error);
    //   }

    //   try {
    //     // 获取指定域名的 Cookie
    //     const cookies = await session.defaultSession.cookies.get({ url: url });
    //     console.log('Cookies:', cookies);
    //     // 将 Cookie 数据存储到本地文件
    //     const cookiesFilePath = path.join(__dirname, id+'cookies.json');
    //     fs.writeFileSync(cookiesFilePath, JSON.stringify(cookies, null, 2));
    //     console.log(`Cookies saved to ${cookiesFilePath}`);
    //   } catch (error) {
    //     console.error('Failed to get cookies:', error);
    //   }

    // });
    
  }
}

ExampleController.toString = () => '[class ExampleController]';
module.exports = ExampleController;  